import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:logger/logger.dart';
import '../models/todo.dart';
import '../services/database_service.dart';
import '../utils/loading_dialog.dart';
import 'todo_edit_screen.dart';

class TodoListScreen extends StatefulWidget {
  const TodoListScreen({super.key});

  @override
  State<TodoListScreen> createState() => _TodoListScreenState();
}

class _TodoListScreenState extends State<TodoListScreen> {
  final DatabaseService _databaseService = DatabaseService();
  List<Todo> _todos = [];
  List<Todo> _filteredTodos = [];
  bool _isLoading = true;
  String _searchQuery = '';
  int _filterStatus = 0; // 0: 全部, 1: 未完成, 2: 已完成
  String _sortBy = 'priority'; // priority, date, title

  @override
  void initState() {
    super.initState();
    _loadTodos();
  }

  Future<void> _loadTodos() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final todos = await _databaseService.getAllTodos();
      setState(() {
        _todos = todos;
        _applyFilter();
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      if (mounted) {
        Logger().i('$e');
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载待办事项失败: $e')),
        );
      }
    }
  }

  void _applyFilter() {
    List<Todo> filtered = List.from(_todos);

    // 应用状态过滤
    if (_filterStatus == 1) {
      filtered = filtered.where((todo) => !todo.isCompleted).toList();
    } else if (_filterStatus == 2) {
      filtered = filtered.where((todo) => todo.isCompleted).toList();
    }

    // 应用搜索过滤
    if (_searchQuery.isNotEmpty) {
      filtered = filtered
          .where((todo) =>
              todo.title.toLowerCase().contains(_searchQuery.toLowerCase()) ||
              (todo.description
                      ?.toLowerCase()
                      .contains(_searchQuery.toLowerCase()) ??
                  false))
          .toList();
    }

    // 应用排序
    switch (_sortBy) {
      case 'priority':
        filtered.sort((a, b) {
          if (a.priority != b.priority) {
            return a.priority.compareTo(b.priority);
          }
          return b.createdAt.compareTo(a.createdAt);
        });
        break;
      case 'date':
        filtered.sort((a, b) => b.createdAt.compareTo(a.createdAt));
        break;
      case 'title':
        filtered.sort((a, b) => a.title.compareTo(b.title));
        break;
    }

    setState(() {
      _filteredTodos = filtered;
    });
  }

  Future<bool> _onWillPop() async {
    if (await _databaseService.shouldSyncDatabase()) {
      final context = this.context;
      if (!context.mounted) return true;

      LoadingDialog.show(context);
      await DatabaseService().syncDatabase();
      if (!context.mounted) return true;

      LoadingDialog.hide(context);
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('待办事项'),
          backgroundColor: Theme.of(context).colorScheme.inversePrimary,
          actions: [
            PopupMenuButton<String>(
              onSelected: (value) {
                setState(() {
                  _sortBy = value;
                  _applyFilter();
                });
              },
              itemBuilder: (context) => [
                const PopupMenuItem(
                  value: 'priority',
                  child: Text('按优先级排序'),
                ),
                const PopupMenuItem(
                  value: 'date',
                  child: Text('按日期排序'),
                ),
                const PopupMenuItem(
                  value: 'title',
                  child: Text('按标题排序'),
                ),
              ],
            ),
          ],
        ),
        body: Column(
          children: [
            _buildSearchAndFilter(),
            _buildStats(),
            Expanded(
              child: _isLoading
                  ? const Center(child: CircularProgressIndicator())
                  : _filteredTodos.isEmpty
                      ? _buildEmptyState()
                      : _buildTodoList(),
            ),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => _navigateToEditScreen(),
          child: const Icon(Icons.add),
        ),
      ),
    );
  }

  Widget _buildSearchAndFilter() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          TextField(
            decoration: const InputDecoration(
              hintText: '搜索待办事项...',
              prefixIcon: Icon(Icons.search),
              border: OutlineInputBorder(),
            ),
            onChanged: (value) {
              setState(() {
                _searchQuery = value;
                _applyFilter();
              });
            },
          ),
          const SizedBox(height: 8),
          Row(
            children: [
              Expanded(
                child: SegmentedButton<int>(
                  segments: const [
                    ButtonSegment<int>(
                      value: 0,
                      label: Text('全部'),
                    ),
                    ButtonSegment<int>(
                      value: 1,
                      label: Text('未完成'),
                    ),
                    ButtonSegment<int>(
                      value: 2,
                      label: Text('已完成'),
                    ),
                  ],
                  selected: {_filterStatus},
                  onSelectionChanged: (Set<int> newSelection) {
                    setState(() {
                      _filterStatus = newSelection.first;
                      _applyFilter();
                    });
                  },
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStats() {
    final completedCount = _todos.where((todo) => todo.isCompleted).length;
    final totalCount = _todos.length;
    final pendingCount = totalCount - completedCount;

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          _buildStatItem('总计', totalCount, Colors.blue),
          _buildStatItem('待完成', pendingCount, Colors.orange),
          _buildStatItem('已完成', completedCount, Colors.green),
        ],
      ),
    );
  }

  Widget _buildStatItem(String label, int count, Color color) {
    return Column(
      children: [
        Text(
          count.toString(),
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey[600],
          ),
        ),
      ],
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.check_circle_outline,
            size: 80,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 16),
          Text(
            _searchQuery.isNotEmpty ? '没有找到相关待办事项' : '暂无待办事项',
            style: TextStyle(
              fontSize: 18,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 8),
          if (_searchQuery.isEmpty)
            Text(
              '点击右下角的按钮添加新的待办事项',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[500],
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildTodoList() {
    return RefreshIndicator(
      onRefresh: _loadTodos,
      child: ListView.builder(
        itemCount: _filteredTodos.length,
        itemBuilder: (context, index) {
          final todo = _filteredTodos[index];
          return _buildTodoItem(todo);
        },
      ),
    );
  }

  Widget _buildTodoItem(Todo todo) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      child: ListTile(
        leading: Checkbox(
          value: todo.isCompleted,
          onChanged: (value) => _toggleTodoComplete(todo.id),
        ),
        title: Text(
          todo.title,
          style: TextStyle(
            decoration: todo.isCompleted ? TextDecoration.lineThrough : null,
            color: todo.isCompleted ? Colors.grey : null,
          ),
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (todo.description != null && todo.description!.isNotEmpty)
              Text(
                todo.description!,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: todo.isCompleted ? Colors.grey : null,
                ),
              ),
            const SizedBox(height: 4),
            Row(
              children: [
                _buildPriorityChip(todo.priority),
                const SizedBox(width: 8),
                if (todo.category != null)
                  Chip(
                    label: Text(todo.category!),
                    backgroundColor: Colors.blue.withOpacity(0.1),
                    labelStyle: const TextStyle(fontSize: 12),
                  ),
                const Spacer(),
                Text(
                  DateFormat('MM/dd').format(todo.createdAt),
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ],
        ),
        trailing: PopupMenuButton<String>(
          onSelected: (value) {
            switch (value) {
              case 'edit':
                _navigateToEditScreen(todo: todo);
                break;
              case 'delete':
                _showDeleteDialog(todo);
                break;
            }
          },
          itemBuilder: (context) => [
            const PopupMenuItem(
              value: 'edit',
              child: Row(
                children: [
                  Icon(Icons.edit),
                  SizedBox(width: 8),
                  Text('编辑'),
                ],
              ),
            ),
            const PopupMenuItem(
              value: 'delete',
              child: Row(
                children: [
                  Icon(Icons.delete),
                  SizedBox(width: 8),
                  Text('删除'),
                ],
              ),
            ),
          ],
        ),
        onTap: () => _navigateToEditScreen(todo: todo),
      ),
    );
  }

  Widget _buildPriorityChip(int priority) {
    Color color;
    String text;
    switch (priority) {
      case 1:
        color = Colors.red;
        text = '高';
        break;
      case 2:
        color = Colors.orange;
        text = '中';
        break;
      case 3:
        color = Colors.green;
        text = '低';
        break;
      default:
        color = Colors.grey;
        text = '中';
    }

    return Chip(
      label: Text(text),
      backgroundColor: color.withOpacity(0.1),
      labelStyle: TextStyle(
        color: color,
        fontSize: 12,
        fontWeight: FontWeight.bold,
      ),
    );
  }

  Future<void> _toggleTodoComplete(String id) async {
    try {
      await _databaseService.toggleTodoComplete(id);
      _loadTodos();
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('操作失败: $e')),
        );
      }
    }
  }

  Future<void> _navigateToEditScreen({Todo? todo}) async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => TodoEditScreen(todo: todo),
      ),
    );

    if (result == true) {
      _loadTodos();
    }
  }

  void _showDeleteDialog(Todo todo) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除待办事项'),
        content: Text('确定要删除"${todo.title}"吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.pop(context);
              try {
                await _databaseService.deleteTodo(todo.id);
                _loadTodos();
                if (mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('删除成功')),
                  );
                }
              } catch (e) {
                if (mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('删除失败: $e')),
                  );
                }
              }
            },
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }
}
